package Chapter25.jdbc.transaction_;

import Chapter25.jdbc.utils.JDBCUtils;
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author 杨森
 * @date 2022年11月20日 15:52
 */
public class Transaction_ {

    //没有使用事物
    @Test
    public void noTransaction() {
        //得到连接
        Connection connection = null;

        //组织一个sql
        String sql = "update account set balance=balance-100 where id=1";
        String sql2 = "update account set balance=balance+100 where id=2";
        PreparedStatement preparedStatement = null;
        //3.创建PreparedStatement对象
        try {
            //在默认情况下，connection对象默认自动提交
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate();//执行第一条sql

            int i=1/0;//异常，下面的语句不会执行
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();//执行第二条sql
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.close(null, preparedStatement, connection);
        }
    }


    //使用事物
    @Test
    public void useTransaction() {
        //得到连接
        Connection connection = null;

        //组织一个sql
        String sql = "update account set balance=balance-100 where id=1";
        String sql2 = "update account set balance=balance+100 where id=2";
        PreparedStatement preparedStatement = null;
        //3.创建PreparedStatement对象
        try {
            //在默认情况下，connection对象默认自动提交
            connection = JDBCUtils.getConnection();
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate();//执行第一条sql

            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();//执行第二条sql

            connection.commit();
        } catch (SQLException e) {
            //这里进行回滚，即撤销执行的SQL
            //默认回滚到事物开始的状态
            System.out.println("执行发生了异常，撤销执行的sql");
            try {
                connection.rollback();

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.close(null, preparedStatement, connection);
        }
    }

}
